package top.kiterunner.learning.concurrency_test;

import java.util.concurrent.TimeUnit;

/**
 * AdorynZhao in Tencent-UESTC.
 * Source Code Created on 2017/7/3.
 * 问题：对业务写方法加锁，对业务读方法不加锁，容易产生脏读问题（Dirty Read）
 * 即正在写的时候读，这个时候会出现问题
 */
public class ThreadDemo3 {

    private String name;
    private double balance;

    public synchronized void set(String name, double balance) {
        this.name = name;

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        this.balance = balance;
    }

    // 在getBalance时设置synchronized，可以防止脏读
    public double getBalance(String name) {
        return this.balance;
    }

    public static void main(String[] args) {
        ThreadDemo3 t3 = new ThreadDemo3();

        new Thread(()->t3.set("zhangsan", 100.0), "Thread_1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Balance = " + t3.getBalance("zhangsan"));

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Balance = " + t3.getBalance("zhangsan"));
    }
}
